package com.milk.servlet;

import com.milk.Dao.StockDao;
import com.milk.entity.Stock;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class StockManagementServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String action = request.getPathInfo().substring(1);
        switch (action) {
            case "viewAll":
                listAllStock(request, response);
                break;
            case "viewById":
                viewStockByDrinkId(request, response);
                break;
            case "update":
                showUpdateStockForm(request, response);
                break;
            case "lowAlert":
                showLowStockAlert(request, response);
                break;
            default:
                // 处理其他不支持的GET请求
                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 设置响应内容类型为HTML，并指定字符编码为UTF-8
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getPathInfo().substring(1);
        switch (action) {
            case "update":
                updateStockQuantity(request, response);
                break;
            default:
                // 处理其他不支持的POST请求
                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    }

    private void listAllStock(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为HTML，并指定字符编码为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // 获取输出流对象
        PrintWriter out = response.getWriter();

        // 查询所有库存信息
        List<Stock> stocks = StockDao.findAll();
        request.setAttribute("stocks", stocks);

        // 转发到库存列表页面（假设为stock_management.jsp）
        request.getRequestDispatcher("/stock_management.jsp").forward(request, response);
    }

    private void viewStockByDrinkId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为HTML，并指定字符编码为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // 获取输出流对象
        PrintWriter out = response.getWriter();

        // 获取要查看库存的饮品ID
        int drinkId = Integer.parseInt(request.getParameter("drinkId"));

        // 根据ID查询库存信息
        Stock stock = StockDao.findByDrinkId(drinkId);
        if (stock != null) {
            // 输出库存信息
            out.println("<html><body>");
            out.println("<h3>饮品ID: " + stock.getDrinkId() + "</h3>");
            out.println("<h3>当前库存数量: " + stock.getQuantity() + "</h3>");
            out.println("<h3>库存预警阈值: " + stock.getLowStockThreshold() + "</h3>");
            out.println("</body></html>");
        } else {
            // 未找到对应的库存信息，返回错误信息
            out.println("<html><body>");
            out.println("<h3>未找到对应饮品的库存信息，请检查输入的ID是否正确。</h3>");
            out.println("</body></html>");
        }
    }

    private void showUpdateStockForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为HTML，并指定字符编码为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // 获取输出流对象
        PrintWriter out = response.getWriter();

        // 输出更新库存数量表单页面（可根据实际情况创建update_stock_form.jsp）
        out.println("<html><body>");
        out.println("<h3>更新库存数量</h3>");
        out.println("<form action='" + request.getContextPath() + "/stock/update' method='post'>");
        out.println("<label for='drinkIdUpdate'>饮品ID</label><input type='text' id='drinkIdUpdate' name='drinkId' placeholder='请输入要更新库存数量的饮品ID'><br>");
        out.println("<label for='newQuantity'>新库存数量</label><input type='number' id='newQuantity' name='newQuantity' placeholder='请输入新的库存数量'><br>");
        out.println("<button type='submit'>更新</button>");
        out.println("</form>");
        out.println("</body></html>");
    }

    private void updateStockQuantity(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取库存信息参数
        int drinkId = Integer.parseInt(request.getParameter("drinkId"));
        int newQuantity = Integer.parseInt(request.getParameter("newQuantity"));

        // 调用StockDao的方法更新库存数量
        int result = StockDao.updateQuantity(drinkId, newQuantity);
        if (result > 0) {
            // 更新成功，重定向到库存列表页面
            response.sendRedirect(request.getContextPath() + "/stock/viewAll");
        } else {
            // 更新失败，返回错误信息
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<html><body>");
            out.println("<h3>更新库存数量失败，请检查输入信息。</h3>");
            out.println("</body></html>");
        }
    }

    private void showLowStockAlert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取库存预警信息
        List<Stock> lowStockList = StockDao.getLowStockAlert();

        // 将低库存预警信息存储在请求属性中
        request.setAttribute("lowStockList", lowStockList);

        // 转发到 low_stock_alert.jsp 页面
        request.getRequestDispatcher("/low_stock_alert.jsp").forward(request, response);
    }
}